<template>
  <diV>
    <el-dialog :visible.sync="dialogVisible" width="600px" center :before-close="handleClose">
      <span class="el-dialog__title" slot="title">注 册</span>
      <!-- 
          model:模型值,他里面的模型值是要提交给后台进行注册的
          form:拿到表单
          rules:校验规则
       -->
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <!-- prop作用: -->
        <el-form-item label="头像" prop="avatar">
          <!-- 
                 action:上传的地址,跟axios没有关系
                 data:上传的时候,需要传递的额外参数,我们现在后台需要传递(它的值是一个对象,对象属性加image,这是后台规定的,值是file类型,也是后台规定的)
                 show-file-list:是否展示上传之后的列表
                 on-success:上传成功之后的回调,做两件事,预览和给form.avatar赋值
                 on-error:上传失败的回调,给他一个提示
                 before-upload:上传之前的回调,可以在这里检查文件类型和大小,还可以给额外参数赋值
              -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="uploadData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱号"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="16" :offset="0">
            <el-form-item label="图形码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入图形码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left: 10px" :span="7">
            <!-- 注册时候的验证码,跟登录的时候不一样 -->
            <img
              :src="registerCodeURL"
              alt=""
              style="width: 100%; heigth: 40px"
              @click="changeregisterCodeURL"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16" :offset="0">
            <el-form-item label="验证码" prop="rcode">
              <el-input
                v-model="form.rcode"
                placeholder="请输入验证码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col style="margin-left: 10px" :span="7">
            <el-button
              size="default"
              @click="getRcode"
              style="width: 100%; heigth: 40px"
              >获取用户验证码</el-button
            >
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="register">确 定</el-button>
      </span>
    </el-dialog>
  </diV>
</template>

<script>
export default {
  name: "Register",
  data() {
    return {
      dialogVisible: false,
      registerCodeURL: `${process.env.VUE_APP_BASEURL}/captcha?type=sendsms`,
      //上传相关
      imageUrl: "", //上传之后的图像地址
      uploadUrl: `${process.env.VUE_APP_BASEURL}/uploads`, //上传的地址
      uploadData: {
        //上传时候的额外参数
        image: null,
      },
      form: {
        //里面的值将来是要提交给后台的,看接口文档
        avatar: "", //头像地址
        username: "", //昵称
        email: "", //邮箱
        phone: "", //手机
        password: "", //密码
        code: "", //图像码
        rcode: "", //验证码
      },
      rules: {
        avatar: [
          {
            required: true,
            message: "头像不能为空",
            trigger: "change",
          },
        ],
        username: [
          {
            required: true,
            message: "昵称不能为空",
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            // validator 是校验器
            validator: (rule, value, callback) => {
              /**
               * rule:校验规则
               * value:用户输入的值
               * callback:校验的结果,无论成功与否都需要调用
               */
              if (!value) {
                return callback(new Error("手机号不能为空"));
              }

              //手机的正则校验
              const reg = /^1[3-9][0-9]{9}$/;
              if (!reg.test(value)) {
                return callback(new Error("手机号不合法"));
              }

              //校验成功不需要加任何参数,但是一定要调用
              callback();
            },
            trigget: "blur", //触发时机
          },
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("邮箱号不能为空"));
              }

              //利用邮箱的正则去进行匹配
              //eslint禁用
              /* eslint-disable */
              const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
              // eslint启用
              /* eslint-enable */
              if (!reg.test(value)) {
                return callback(new Error("邮箱号不合法"));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 6,
            max: 16,
            message: "密码必须在6-16位之间",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "图形码不能为空",
            trigger: "blur",
          },
        ],
        rcode: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //重新获取图形验证码
    changeregisterCodeURL() {
      this.registerCodeURL = `${
        process.env.VUE_APP_BASEURL
      }/captcha?type=sendsms&t=${new Date() - 0}`;
    },
    //   获取验证码
    async getRcode() {
      //判断用户是否输入了手机号和图形验证码
      //校验部分字段
      let isOK = 0;
      this.$refs.form.validateField(["phone"], (errorMessage) => {
        if (!errorMessage) {
          isOK++;
        }
      });
      this.$refs.form.validateField(["code"], (errorMessage) => {
        if (!errorMessage) {
          isOK++;
        }
      });
      if (isOK === 2) {
        const res = await this.$axios.post("/sendsms", {
          phone: this.form.phone,
          code: this.form.code,
        });
        if (res.code === 200) {
          this.form.rcode = res.data.captcha;
        } else {
          this.changeregisterCodeURL();
          this.$message.error(res.message);
        }
      }
    },
    //上传相关的方法
    //上传成功之后
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        //实现预览
        this.imageUrl = URL.createObjectURL(file.raw);
        //给form.avatar
        this.form.avatar = res.data.file_path;
      } else {
        this.$message.error(res.message);
      }
    },
    //上传失败
    handleAvatarError(err) {
      console.log(err);
      this.$message.error("上传失败");
    },
    //上传之前
    //需要先判断图片格式和大小
    beforeAvatarUpload(file) {
      const isImage =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("上传头像图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      //给需要传递的额外参数赋值
      this.uploadData.image = file;
      return isImage && isLt2M;
    },
    //注册
    register() {
      // console.log(this.$refs.form);
      this.$refs.form.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        // delete this.form.code;// delete删除不需要上传注册的属性
        const res = await this.$axios.post("/register", this.form);
        if (res.code === 200) {
          this.$message.success("注册成功");
          this.dialogVisible = false;
          this.$refs.form.resetFields();
        } else {
          this.$message.error("注册失败");
          this.changeRegisterCodeURL();
        }
      });
    },

    //监听关闭的方法
    handleClose(){
      //前提 : 每一项 el-form-item 要设置好prop
      this.$refs.form.resetFields();
      this.imageUrl = '' //清空预览

      this.dialogVisible = false
    }
  },
};
</script>

<style lang="less">
// 在当前的页面中使用less
.avatar-uploader {
  display: flex;
  justify-content: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>